import { createRouter, createWebHistory } from 'vue-router'
import { ElMessage } from 'element-plus'
import Cookies from 'js-cookie' // 引入 js-cookie
import { useUserStore } from '@/store/userStore'

const router = createRouter({
  history: createWebHistory(),
  routes: [
    {
      path: '/',
      redirect: '/screen'
    },
    {
      path: '/login',
      name: 'login',
      component: () => import('@/views/login/LoginView.vue')
    },
    {
      path: '/screen',
      name: 'screen',
      component: () => import('@/views/screen/DataScreen.vue'),
      meta: {
        title: '数据大屏',
      }
    },
    {
      path: '/video',
      name: 'video',
      component: () => import('@/views/video/Video.vue'),
      meta: {
        title: '视频预览',
      }
    },
    {
      path: '/test',
      name: 'MyTest',
      component: () => import('@/views/test/MyTest.vue'),
      meta: {
        title: '测试',
      }
    }
  ]
})

// 路由守卫
router.beforeEach(async (to, from, next) => {
  console.log(to, '==to==')
  //判断是否是login页面或测试页面
  if (to.path === '/login' || to.path === '/test/video') {
    next()
  } else {
    let token: string = to.query.token as string
    if (!token) { // 如果token不存在
      //从Cookie中获取token
      token = Cookies.get('token')
      //验证token是否有效，如果有效，则跳转到首页
      if (token) {
        const userStore = useUserStore()
        await userStore.fetchUserInfo() // 获取用户信息
        await userStore.fetchStationConfig() // 获取单站配置
        next()
      } else {
        ElMessage.warning('请从氚云系统进入')
        next('/login')
      }
    } else {
      // 如果token存在
      Cookies.set('token', token) // 设置token
      const userStore = useUserStore()
      await userStore.fetchUserInfo() // 获取用户信息
      //将url中的token参数删除
      next({ path: to.path, query: { ...to.query, token: undefined } })
    }
  }
})

export default router